//
//  AppealPhoneNoController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/21.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class AppealPhoneNoController: UIViewController {
    
    
    var panelView: UIView  = {
        let panelView = UIView()
        panelView.backgroundColor = UIColor.white
        return panelView
    }()
    
    var originalPhoneNumberTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入原手机号码"
        textField.keyboardType = .phonePad
        textField.text = ""
        let imageView = UIImageView(image: UIImage.init(named: "Icon_手机")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var currentPhoneNumberTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入需要绑定的现手机号码"
        textField.keyboardType = .phonePad
        
        let imageView = UIImageView(image: UIImage.init(named: "Icon_手机")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var securityTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入短信验证码"
        textField.keyboardType = .numberPad
        
        let imageView = UIImageView(image: UIImage.init(named: "reply_n")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.isSecureTextEntry = true
        textField.placeholder = "请输入6-16位字母/数字密码"
        textField.keyboardType = .asciiCapable
        
        let imageView = UIImageView(image: UIImage.init(named: "ic_lock")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var nextStepButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        button.setTitle("下一步", for: .normal)
        button.layer.cornerRadius = 6
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        
        return button
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "现手机号验证"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.nextStepButton.addTarget(self, action: #selector(doNextStepButton), for: .touchUpInside)

        self.setupViews()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func setupViews() {
        self.view.addSubview(self.panelView)
        self.panelView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
        }
        
        self.panelView.addSubview(self.originalPhoneNumberTextField)
        self.originalPhoneNumberTextField.snp.makeConstraints { (make) in
            make.top.right.equalTo(self.panelView)
            make.left.equalTo(self.panelView).offset(10)
            make.height.equalTo(50)
        }
        
        let grayLine1 = UIView()
        grayLine1.backgroundColor = UIColor.mg_backgroundGray
        self.panelView.addSubview(grayLine1)
        grayLine1.snp.makeConstraints { (make) in
            make.top.equalTo(self.originalPhoneNumberTextField.snp.bottom)
            make.right.left.equalTo(self.panelView)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.currentPhoneNumberTextField)
        self.currentPhoneNumberTextField.snp.makeConstraints { (make) in
            make.right.equalTo(self.panelView)
            make.top.equalTo(grayLine1.snp.bottom)
            make.left.equalTo(self.panelView).offset(10)
            make.height.equalTo(self.originalPhoneNumberTextField)
        }
        
        let grayLine2 = UIView()
        grayLine2.backgroundColor = UIColor.mg_backgroundGray
        self.panelView.addSubview(grayLine2)
        grayLine2.snp.makeConstraints { (make) in
            make.top.equalTo(self.currentPhoneNumberTextField.snp.bottom)
            make.right.left.equalTo(self.panelView)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(securityTextField)
        self.securityTextField.snp.makeConstraints { (make) in
            make.right.equalTo(self.panelView)
            make.top.equalTo(grayLine2.snp.bottom)
            make.left.equalTo(self.panelView).offset(10)
            make.height.equalTo(self.originalPhoneNumberTextField)
        }
        
        let button = UIButton()
        button.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 10
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.setTitle("获取验证码", for: .normal)
        button.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        self.panelView.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.left.equalTo(self.securityTextField.snp.right)
            make.centerY.equalTo(self.securityTextField)
            make.right.equalTo(self.panelView).offset(-15)
            make.size.equalTo(CGSize.init(width: 80, height: 30))
        }
        
        let grayLine3 = UIView()
        grayLine3.backgroundColor = UIColor.mg_backgroundGray
        self.panelView.addSubview(grayLine3)
        grayLine3.snp.makeConstraints { (make) in
            make.top.equalTo(self.securityTextField.snp.bottom)
            make.right.left.equalTo(self.panelView)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.passwordTextField)
        self.passwordTextField.snp.makeConstraints { (make) in
            make.right.equalTo(self.panelView)
            make.left.equalTo(self.panelView).offset(10)
            make.height.equalTo(50)
            make.top.equalTo(grayLine3.snp.bottom)
            make.bottom.equalTo(self.panelView).offset(10)
        }
        
        self.view.addSubview(self.nextStepButton)
        self.nextStepButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.panelView.snp.bottom).offset(60)
            make.width.equalTo(200)
            make.height.equalTo(40)
        }
    }
    
    func doCountDownAction(_ button: UIButton) {
        guard let oldPhoneNumber = self.originalPhoneNumberTextField.text, oldPhoneNumber.characters.count > 0 else {
            WWError("请输入旧手机号码后再获取")
            return
        }
        guard Tool.isValidatePhoneNum(oldPhoneNumber) else {
            WWError("请输入11位正确的旧手机格式")
            return
        }
        guard let newPhoneNumber = self.currentPhoneNumberTextField.text, newPhoneNumber.characters.count > 0 else {
            WWError("请输入新的手机号码")
            return
        }
        guard Tool.isValidatePhoneNum(newPhoneNumber) else {
            WWError("请输入11位正确的新手机格式")
            return
        }
        
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        CommonModel.checkPhoneNumberWithoutToken(oldPhoneNumber, needPhoneExist: true) { (response) in
            if response.success {
//                CommonModel.checkPhoneNumberWithoutToken(newPhoneNumber, needPhoneExist: false) { (response) in
//                    if response.success {
                        button.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: button.backgroundColor!, countColor: UIColor.gray)
                        
                    UserModel.requestSecurityCode(phoneNumber: newPhoneNumber, flag: FlagType.agentapply) { (response) in
                            if response.success {
                                #if DEBUG
                                    WWInform(response.value ?? "好像是空的")
                                #else
                                #endif
                            }
                            else {
                                WWInform(response.message)
                            }
                        }
//                    }
//                    else {
//                        WWError("新手机" + response.message)
//                    }
//                }
            }
            else {
                 WWError("旧手机" + response.message)
            }
        }
    }
    
    @objc func doNextStepButton() {
        guard let oldPhoneNumber = self.originalPhoneNumberTextField.text, oldPhoneNumber.characters.count > 0 else {
            WWError("请输入手机号码后再获取")
            return
        }
        guard Tool.isValidatePhoneNum(oldPhoneNumber) else {
            WWError("请输入11位正确的旧手机格式")
            return
        }
        guard let newPhoneNumber = self.currentPhoneNumberTextField.text, newPhoneNumber.characters.count > 0 else {
            WWError("请输入新的手机号码")
            return
        }
        guard Tool.isValidatePhoneNum(newPhoneNumber) else {
            WWError("请输入11位正确的新手机格式")
            return
        }
        guard let verifyCode = self.securityTextField.text, verifyCode.characters.count > 0  else {
            WWError("请输入验证码")
            return
        }
        guard let password = self.passwordTextField.text, password.characters.count >= 6, password.characters.count <= 16 else {
            WWError("密码有误，请输入6-16位密码")
            return
        }
        
        WWBeginLoadingWithStatus("开始提交")
        UserModel.checkPhoneNumber(oldPhoneNumber, currentPhoneNumber: newPhoneNumber, verifyCode: verifyCode) { (response) in
            if response.success {
                WWSuccess("验证成功")
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    let form = ["LealPersonOldPhone": oldPhoneNumber, "LealPersonPhone": newPhoneNumber, "Password": password]
                    
                    
                    let vc = CertificationSubmitController(CertificationSubmitController.ControllerStyle.appeal)
                   // vc.navigationItem.hidesBackButton = true
                    
                    vc.form = form
                self.navigationController?.pushViewController(vc, animated: true)
                    
                })
            }
            else {
                WWError(response.message)
            }
        }
    }

}
